import * as THREE from "three";
// 渲染器通道
import { RenderPass } from "three/addons/postprocessing/RenderPass.js";
// 效果器
import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js";
// 发光通道
import { UnrealBloomPass } from "three/addons/postprocessing/UnrealBloomPass.js";
// 输出通道
import { OutputPass } from "three/addons/postprocessing/OutputPass.js";
// 着色器通道
import { ShaderPass } from "three/addons/postprocessing/ShaderPass.js";

const params = {
  threshold: 1,
  strength: 1, // 强度
  radius: 0.84, // 半径
  exposure: 1.55, // 扩散
};
export default function unreal(
  scene: THREE.Scene,
  camera: THREE.PerspectiveCamera,
  renderer: THREE.WebGLRenderer
) {
  // 渲染器通道，将场景全部加入渲染器
  const renderScene = new RenderPass(scene, camera);
  // 添加虚幻发光通道
  const bloomPass = new UnrealBloomPass(
    new THREE.Vector2(innerWidth, innerHeight),
    1.5,
    0.4,
    0.85
  );
  bloomPass.threshold = params.threshold;
  bloomPass.strength = params.strength;
  bloomPass.radius = params.radius;

  // 创建合成器
  const bloomComposer = new EffectComposer(renderer);
  bloomComposer.renderToScreen = false;
  // 将渲染器和场景结合到合成器中
  bloomComposer.addPass(renderScene);
  bloomComposer.addPass(bloomPass);

  // 着色器通道
  const mixPass = new ShaderPass(
    // 着色器
    new THREE.ShaderMaterial({
      uniforms: {
        baseTexture: { value: null },
        bloomTexture: { value: bloomComposer.renderTarget2.texture },
      },
      vertexShader: `
            
            varying vec2 vUv;
    
            void main() {
    
                vUv = uv;
    
                gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
    
            }
            
            `,
      fragmentShader: `
            
            uniform sampler2D baseTexture;
            uniform sampler2D bloomTexture;
    
            varying vec2 vUv;
    
            void main() {
    
                gl_FragColor = ( texture2D( baseTexture, vUv ) + vec4( 1.0 ) * texture2D( bloomTexture, vUv ) );
    
            }
    
            `,
      defines: {},
    }),
    "baseTexture"
  );
  mixPass.needsSwap = true;

  // 合成器输出通道
  const outputPass = new OutputPass();

  const finalComposer = new EffectComposer(renderer);
  finalComposer.addPass(renderScene);
  finalComposer.addPass(mixPass);
  finalComposer.addPass(outputPass);

  return {
    finalComposer,
    bloomComposer,
    renderScene,
    bloomPass,
  };
}
